package ru.nsu.fit.iconveyor.conveyor.storage.importer;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import ru.nsu.fit.iconveyor.conveyor.Conveyor;
import ru.nsu.fit.iconveyor.conveyor.Globals;
import ru.nsu.fit.iconveyor.conveyor.storage.importer.graphml.GraphMLDecoder;
import ru.nsu.fit.iconveyor.conveyor.node.Node;
import ru.nsu.fit.iconveyor.conveyor.utils.jar.JarClassLoader;
import ru.nsu.fit.iconveyor.conveyor.utils.zip.Unzip;

/**
 * This class make import from icon file to class conveyor.
 *
 * @author Timur Zolotuhin (tzolotuhin@gmail.com)
 */
public class Importer {
    public static Conveyor importFromFile(String fileName) throws Exception {
        // unzip archive
        File myTempDir = File.createTempFile("install", "dir");
        myTempDir.delete();
        myTempDir.mkdirs();
        Unzip.unzip(fileName, myTempDir.getAbsolutePath());

        // load executors
        Map<String, Class<Node>> executors = new HashMap<String, Class<Node>>();
        try {
            JarClassLoader classLoader = new JarClassLoader(myTempDir.getAbsolutePath() + File.separator + Globals.JAR_FILE_NAME_IN_ARCHIVE);
            for (String className : classLoader.getClasses()) {
                Class<?> clazz = classLoader.getClass(className);
                try {
                    Class<Node> nodeClass = (Class<Node>)clazz;
                    executors.put(className, nodeClass);
                } catch (Exception ex) {}
            }
        } catch (FileNotFoundException ex) {

        }

        // load properties
        Properties prop = new Properties();
        FileInputStream prop_fis = null;
        try {
            prop_fis = new FileInputStream(myTempDir.getAbsolutePath() + File.separator + Globals.PROPERTIES_FILE_NAME_IN_ARCHIVE);
            prop.load(prop_fis);
        } catch (FileNotFoundException ex) {
        } finally {
            if (prop_fis != null) {
                try {
                    prop_fis.close();
                } catch (Exception ex) {
                }
            }
        }

        // load conveyor
        Conveyor conv = new GraphMLDecoder().decode(myTempDir.getAbsolutePath() + File.separator + Globals.GRAPHML_FILE_NAME_IN_ARCHIVE, executors, prop);
        return conv;
    }
}
